package cn.wolfcode.Utlis;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class oSSUtlis {
     @Value("${aliyun.oss.endpoint}")
     private String endpoint;
     @Value("${aliyun.oss.acessKeyId}")
      private String accessKeyId;
      @Value("${aliyun.oss.accessKeySecret}")
      private String accessKeySecret;
      @Value("${aliyun.oss.bucketName}")
      private String bucketName;

      //文件上传
    public  String upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newfileName = UUID.randomUUID().toString() + substring;
        //创建ossClient的实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, newfileName, inputStream);
        ossClient.shutdown();
        inputStream.close();
        StringBuffer url = new StringBuffer(endpoint);
        return url.insert(8,bucketName+".").append("/").append(newfileName).toString();
    }
}
